package com.yzdbx.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.yzdbx.utils.DbUtil;
import com.yzdbx.utils.GenUtil;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static com.yzdbx.task.PurchaseRunnable.GEN_PURCHASE_IDS;
import static com.yzdbx.task.SalefOrderRunnable.GEN_ORDER_IDS;
import static com.yzdbx.utils.DbUtil.getMaxId;

/**
 * @BelongsProject: SERVEVICE-DATA-GEN
 * @BelongsPackage: com.yzdbx.task
 * @Author: lk
 * @CreateTime: 2025-05-14
 * @Description: TODO
 * @Version: 1.0
 */
public class PurchaseShouHuoRunnable implements Exe {

    private Connection connection;

    public PurchaseShouHuoRunnable(Connection connection) {
        this.connection = connection;
    }

    public static final ThreadLocal<List<Integer>> FAHUO_IDS = new ThreadLocal<>();

    @Override
    public boolean execute(int count) {
        //拿到生成的销售订单明细
        List<Integer> purchaseIds = GEN_PURCHASE_IDS.get();
        if (CollectionUtil.isEmpty(purchaseIds)) return Boolean.FALSE;

        List<Integer> huoshouIds = new ArrayList<>();

        int daohuoId = getMaxId(connection, "purchaseOfManifests");
        int ckdId = getMaxId(connection, "ck03Listing");
        for (int i = 1; i <= purchaseIds.size(); i++) {
            int curId = daohuoId + i;
            String daohuodanhao = GenUtil.getNoFromTable(connection, "CGDH", "purchaseOfManifests", "purchaseOfManifestNumber");
            //查询销售订单
            Map<String, Object> saleOrder = DbUtil.getById(connection, "cgPurchaseOrderForms", purchaseIds.get(i - 1));
            //查询销售订单明细
            List<LinkedHashMap<String, Object>> details;
            try {
                PreparedStatement statement = connection.prepareStatement("select * from breakdownOfPurchaseOrders where associatedPurchaseOrders = ?");
                statement.setInt(1, purchaseIds.get(i - 1));
                ResultSet resultSet = statement.executeQuery();
                details = DbUtil.resultSetToList(resultSet);

                int finalI = i;
                List<LinkedHashMap<String, Object>> associatedPurchase = details.stream().filter(cur -> cur.get("associatedPurchaseOrders").equals(purchaseIds.get(finalI - 1))).toList();

                int maxId = getMaxId(connection, "procurementArrivalDetails");
                int totalArrivals = 0;
                BigDecimal totalAmount = BigDecimal.ZERO;
                for (int j = 1; j <= associatedPurchase.size(); j++) {
                    PreparedStatement preparedStatement = connection.prepareStatement("insert into procurementArrivalDetails (id,productInformation,numberOfShipmentsReceived,unitPrice,amount,numberOfRefunds,numberOfPurchaseOrders,linksToManifests,synchronisingFolderFailedSS,created) values (" +
                            "?,?,?,?,?,?,?,?,?,?)");
                    preparedStatement.setInt(1, ++maxId);
                    preparedStatement.setInt(2, Integer.parseInt(associatedPurchase.get(j - 1).get("procurementInformation").toString()));
                    int procurementVolume = new BigDecimal(associatedPurchase.get(j - 1).get("procurementVolume").toString()).intValue();
                    totalArrivals+=procurementVolume;
                    preparedStatement.setInt(3, procurementVolume);
                    preparedStatement.setBigDecimal(4, BigDecimal.valueOf(Double.parseDouble(associatedPurchase.get(j - 1).get("unitPrice").toString())));
                    BigDecimal total = BigDecimal.valueOf(Double.parseDouble(associatedPurchase.get(j - 1).get("unitPrice").toString()) * procurementVolume).setScale(2, BigDecimal.ROUND_HALF_UP);
                    totalAmount = totalAmount.add(total);
                    preparedStatement.setBigDecimal(5, total);
                    preparedStatement.setInt(6, 0);
                    preparedStatement.setInt(7, procurementVolume);
                    preparedStatement.setInt(8, curId);
                    preparedStatement.setString(9, saleOrder.get("synchronisingFolderFailedSS").toString());
                    preparedStatement.setTimestamp(10, GenUtil.CUR_TIME_STAMP.get());
                    preparedStatement.execute();
                }
                //创建到货单
                PreparedStatement statement2 = connection.prepareStatement("insert into purchaseOfManifests (id,purchaseOfManifestNumber,dateOfArrival,consignee,clientInformation,totalArrivals,amountOfGoodsToBeDelivered,synchronisingFolderFailedSS,created,approvalStatus,associatedPurchaseOrderInformati) values (?,?,?,?,?,?,?,?,?,?,?)");
                statement2.setInt(1, curId);
                statement2.setString(2, GenUtil.getNoFromTable(connection, "WB-", "purchaseOfManifests", "purchaseOfManifestNumber"));
                statement2.setTimestamp(3, GenUtil.CUR_TIME_STAMP.get());
                statement2.setString(4, saleOrder.get("synchronisingFolderFailedSS").toString());
                statement2.setInt(5, Integer.parseInt(saleOrder.get("associatedSuppliers").toString()));
                statement2.setInt(6, totalArrivals);
                statement2.setBigDecimal(7,totalAmount );
                statement2.setString(8, saleOrder.get("synchronisingFolderFailedSS").toString());
                statement2.setTimestamp(9, GenUtil.CUR_TIME_STAMP.get());
                statement2.setString(10, "已通过");
                statement2.setInt(11, Integer.parseInt(saleOrder.get("id").toString()));

                statement2.execute();

                //创建入库明细
                int ckmxId = getMaxId(connection, "ck04ListOfEntriesListOfEntries");
                int curCkdId = ckdId + i;

                for (int j = 1; j <= associatedPurchase.size(); j++) {
                    PreparedStatement preparedStatement = connection.prepareStatement("insert into ck04ListOfEntriesListOfEntries(id,productInformation,numberOfEntries,linkToList) values (?,?,?,?)");
                    preparedStatement.setInt(1, ++ckmxId);
                    preparedStatement.setInt(2, Integer.parseInt(associatedPurchase.get(j - 1).get("procurementInformation").toString()));
                    preparedStatement.setInt(3, new BigDecimal(associatedPurchase.get(j - 1).get("procurementVolume").toString()).intValue());
                    preparedStatement.setInt(4, curCkdId);
                    preparedStatement.execute();
                }
                //创建入库单
                PreparedStatement statement3 = connection.prepareStatement("insert into ck03Listing (id,repositoryNumber,operator,repositoryDate,approvalStatus,associatedSuppliers,documentType) values (?,?,?,?,?,?,?)");
                statement3.setInt(1, curCkdId);
                statement3.setString(2, GenUtil.getNoFromTable(connection, "RK", "ck03Listing", "repositoryNumber"));
                statement3.setString(3, saleOrder.get("synchronisingFolderFailedSS").toString());
                statement3.setTimestamp(4,GenUtil.CUR_TIME_STAMP.get());
                statement3.setString(5, "已通过");
                statement3.setInt(6, Integer.parseInt(saleOrder.get("associatedSuppliers").toString()));
                statement3.setString(7, "采购入库");
                statement3.execute();
                huoshouIds.add(curId);

            } catch (Exception e) {
                throw new RuntimeException("数据生成失败",e);
            }

        }

        FAHUO_IDS.set(huoshouIds);
        return Boolean.TRUE;
    }
}
